package com.daylightrobbery.server.packet;

import com.daylightrobbery.server.packet.type.DataPacket;
import com.daylightrobbery.utils.ObjectMapperUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class DataPacketFactory implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger log = LoggerFactory.getLogger(DataPacketFactory.class);

    Map<Integer, Class<?>> dataPackets = new HashMap<>();

    public DataPacketFactory(){

    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String, DataPacket> beansOfType = event.getApplicationContext().getBeansOfType(DataPacket.class);
        beansOfType.forEach(((s, dataPacket) -> {
            log.info("加载[" + dataPacket.getType() + "] " + dataPacket.getClass().toString());
            dataPackets.put(dataPacket.getType(), dataPacket.getClass());
        }));
    }

    public DataPacket getDataPacketsByType(GamePacket gamePacket){
        return (DataPacket) ObjectMapperUtil.toObject(gamePacket.getData(), dataPackets.get(gamePacket.getType()));
    }


}
